package com.butterfly.mvc.util;

import com.butterfly.mvc.servlet.ActionBean;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.lang.reflect.Field;
import java.util.ArrayList;
import java.util.Map;

/**
 * Created by WOLF on 2016/9/19.
 */
public class Param2Bean {

    public static Object[] packageParam(HttpServletRequest request, HttpServletResponse response, Class[] params){
        if(params == null || params.length == 0){
            return null;
        }
        Object[] rst = new Object[params.length];


        for(int i=0;i<params.length;i++){
            Class c = params[i];
            if("javax.servlet.http.HttpServletRequest".equals(c.getName())){
                rst[i] = request;
            }else if("javax.servlet.http.HttpServletResponse".equals(c.getName())){
                rst[i] = response;
            }else{
                Object param = null;
                try{
                    //Class clazz = Class.forName(params[i].getName());
                    Class clazz = c;
                    param =  clazz.newInstance();

                    /**获取当前类及所有父类的属性**/
                    ArrayList<Field> filedList = new ArrayList<Field>();
                    do{
                        Field[] fields = clazz.getDeclaredFields();
                        for(Field f:fields){
                            filedList.add(f);
                        }
                        clazz = clazz.getSuperclass();
                    }while (clazz != Object.class);

                    for (Field f:filedList){
                        String val = request.getParameter(f.getName());
                        if(val != null) {
                            f.setAccessible(true);
                            f.set(param, val);
                            f.setAccessible(false);
                        }
                    }
                    rst[i] = param;
                }catch (Exception e){
                    System.out.println("封装参数失败");
                    e.printStackTrace();
                }
            }
        }

        return rst;
    }

    public static String getPath(HttpServletRequest request){
        return request.getServletPath().split("\\.")[0];
    }

}
